// 获取元素
const form = document.querySelector('#loginform')
const img = document.querySelector('#loginform img')
const span = document.querySelector('#loginform span')
// 验证码渲染
async function render() {
  try {
    const { data: res } = await axios.get('/captcha/image')
    console.log(res)
    localStorage.setItem('captchaKey', res.data.key)
    img.src = res.data.base64
  } catch {
    tip('请检查您的网络')
  }
}
render()
img.addEventListener('click', function () {
  render()
})

//点击验证码事件

{
  let flag = true
  span.addEventListener('click', async function () {
    if (flag) {
      const fd = serialize(form, { hash: true })
      fd.captchaKey = localStorage.getItem('captchaKey')
      console.log(fd)
      const phone = /^(?:(?:\+|00)86)?1\d{10}$/
      if (!phone.test(fd.mobile)) return tip('请输入正确的手机号')
      if (!fd.captchaCode) return tip('请输入图形验证码')
      try {
        const { data: res } = await axios.post('/captcha/sendSmsCaptcha', {
          form: fd
        })
        if (res.status === 200) {
          let i = 60
          span.innerHTML = `重新发送(60)秒`
          span.classList.add('active')
          flag = false
          let timer = setInterval(function () {
            i--
            span.innerHTML = `重新发送(${i})秒`
            if (i === 0) {
              clearInterval(timer)
              span.innerHTML = `重新发送`
              flag = true
              span.classList.remove('active')
            }
          }, 1000)
        }
        tip(res.message)
      } catch (error) {
        tip('获取验证码失败,请检查网络')
      }
    }
  })
}

// 提交表单事件
form.addEventListener('submit', async function (e) {
  e.preventDefault()
  const fd = serialize(form, { hash: true })
  fd.isParty = false
  fd.partyData = {}
  console.log(fd)
  const phone = /^(?:(?:\+|00)86)?1\d{10}$/
  if (!phone.test(fd.mobile)) return tip('请输入正确的手机号')
  if (!fd.captchaCode) return tip('请输入图形验证码')
  try {
    const { data: res } = await axios.post('/passport/login', { form: fd })
    console.log(res)
    tip(res.message)
    if (res.status === 200) {
      localStorage.setItem('userToken', res.data.token)
      localStorage.setItem('userId', res.data.userId)
      setTimeout(function () {
        location.href = './index.html'
      }, 500)
    }
  } catch (error) {
    console.dir(error)
    tip('请检查网络')
  }
})
